/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Global Trust Authority is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

use std::future::Future;
use std::pin::Pin;

use common_log::{error, info};
use policy::api::get_export_policy::get_export_policy;
use policy_engine::evaluate_policy;

use crate::{
    chain::attestation_chain::{AttestationHandler, AttestationContext},
    error::attestation_error::AttestationError,
};

/// Handler for exporting policy in the attestation chain
pub struct ExportPolicyHandler {
    next: Option<Box<dyn AttestationHandler>>,
}

impl ExportPolicyHandler {
    pub fn new() -> Self {
        Self { next: None }
    }

    /// Evaluate export policy for the given evidence and attester type
    fn evaluate_export_policy(
        &self,
        verify_evidence: &serde_json::Value,
        attester_type: &str,
    ) -> Result<Option<serde_json::Value>, AttestationError> {
        info!("Evaluating export policy for attester type: {}", attester_type);
        let export_policy = match get_export_policy(attester_type) {
            Ok(policy) => policy,
            Err(e) => {
                error!("Failed to get export policy for attester type: {}, error: {}", attester_type, e);
                return Err(AttestationError::PolicyNotFoundError(e.to_string()));
            },
        };

        match evaluate_policy(verify_evidence, &export_policy) {
            Ok(result) => {
                if result == serde_json::json!({}) {
                    Ok(None)
                } else {
                    Ok(Some(result))
                }
            },
            Err(e) => {
                error!("Failed to evaluate export policy: {}", e);
                Err(AttestationError::PolicyVerificationError(e.to_string()))
            },
        }
    }
}

impl AttestationHandler for ExportPolicyHandler {
    fn handle<'a>(&'a self, context: &'a mut AttestationContext) -> Pin<Box<dyn Future<Output = Result<(), AttestationError>> + Send + 'a>> {
        Box::pin(async move {
            if let Some(verify_evidence) = &context.verify_evidence {
                let export_result = self.evaluate_export_policy(
                    verify_evidence,
                    &context.evidence.attester_type,
                )?;
                context.raw_evidence = export_result;
            }
            Ok(())
        })
    }
    
    fn set_next(&mut self, next: Box<dyn AttestationHandler>) {
        self.next = Some(next);
    }
    
    fn get_next(&self) -> Option<&dyn AttestationHandler> {
        self.next.as_ref().map(|h| h.as_ref())
    }
    
    fn name(&self) -> &'static str {
        "ExportPolicy"
    }
}